<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 

<?php 
require "hrfuns.php"; 
Valid_Client();
$iSQL = GetSQL();
?>

<?php
const DATADIR = "data";
function GetDepartId($iSQL, $depart_name)
{
    if (is_numeric($depart_name))
        return $depart_name;

    $sqlstr = "select depart_id from depart_t"
            . " where depart_name = '" . $depart_name . "'";

    if ($result = $iSQL->query($sqlstr)) {
        $row = $result->fetch_assoc();
        return $row["depart_id"];
    }
    else
        return 0;
}

function import($iSQL, $table, $filename)
{
    $sqlstr = "select * from $table";

    if ($result = $iSQL->query($sqlstr)) {
        $finfo = $result->fetch_fields();
        $result->close();

        $field_count = count($finfo);

        if ($file = fopen($filename, "r")) {
            while ($line = fgets($file)) {
                $line = trim($line);

                if (strlen($line) == 0) continue;
                if ($line[0] == "#") continue;

                $fields = split(",", $line);
                $sqlstr = "insert into $table values(";
                for ($i = 0; $i < $field_count; $i++) {
                    if ($i != 0) $sqlstr .= ", ";

                    switch ($finfo[$i]->type) {
                        case TYPE_VARCHAR:
                        case TYPE_CHAR:
                            $sqlstr .= "'" . trim($fields[$i]) . "'";
                            break;
                        case TYPE_INT:
                        case TYPE_FLOAT:
                        default:
                            if ($finfo[$i]->name == "em_depart_id") {
                                $sqlstr .= GetDepartId($iSQL, trim($fields[$i]));
                            }
                            else
                                $sqlstr .= trim($fields[$i]);
                            break;
                    }
                } // for ($i
                $sqlstr .= ")";
                echo "$sqlstr";
                $ret = $iSQL->query($sqlstr);
                if ($ret) echo " ... <font color=green>Passed</font><br>\n";
                else echo " ... <font color=red>Failed</font><br>\n";
            } // while ($line
        }
        fclose($file);
        echo "Done.\n";
    } 
}
?>

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
</head>
<body>
<?php
if (isset($_POST["submit"])) {

    $fileImport = $_FILES["txtFile"]["tmp_name"];
    
    import($iSQL, $_POST["selTableName"], $fileImport);

}
?>
</body>

<?php $iSQL->close(); ?>
